package com.hd.trans.ui.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Pair;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityOptionsCompat;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hd.trans.TranslationEntry;
import com.hd.trans.TranslationInterior;
import com.hd.trans.config.CallbackProperty;
import com.hd.trans.config.ThemeProperty;
import com.hd.trans.config.TranslationProperty;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.db.bean.HuDunLanguage;
import com.hd.trans.db.bean.LanguageTips;
import com.hd.trans.db.greenDao.DaoMaster;
import com.hd.trans.framework.rom.IOUtils;
import com.hd.trans.framework.tools.ThreadPoolWrapper;
import com.hd.trans.homefun.HomeFun;
import com.hd.trans.limit4Use.LimitUseListener;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.network.apiService.UrlConstant;
import com.hd.trans.network.bean.UserInfoBean;
import com.hd.trans.track.TrackerListener;
import com.hd.trans.ui.component.RecordFileCallback;
import com.hd.trans.ui.service.NetworkTaskService;
import com.hd.trans.utils.Constant;
import com.hd.trans.utils.DomainManager;
import com.hd.trans.utils.LogUtil;
import com.translation.assistant.utils.SensitiveWordsCheck;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Predicate;

/**
 * 添加了TranslationEntry作为SDK初始化的入口类，
 * 该类不再作为正式的初始化类。
 * 初始化数据库，
 * 初始化语言tips，
 * 初始化语言禁用列表，
 * 配置URL。
 */
@Deprecated
public class TransInit {
    /**
     * 私有构造
     */
    private TransInit() {}

    private static HomeFun homeFunListener;
    private static boolean isOpenDomainSwitch;//主备域名自动切换开关
    private static boolean isOpenHuaweiService;//华为服务开关
    private static HashMap<String, LanguageTips> languageTipsMap;
    private static List<String> disableLanguages = new ArrayList<>();
    private static TranslationProperty.Builder translationPropertyBuilder = new TranslationProperty.Builder();
    private static ThemeProperty.Builder themePropertyBuilder = new ThemeProperty.Builder();
    private static CallbackProperty.Builder callbackPropertyBuilder = new CallbackProperty.Builder();

    public static Boolean noneInvalid(){
        if(AppContextProvider.getContext() == null /*|| homeFunListener == null*/){
            return false;
        }
        return true;
    }

    public static HashMap<String, LanguageTips> getLanguageTipsMap(){

        return languageTipsMap;
    }

    //获取全局主题色
    public static int getPrimaryColor() {
        return TranslationInterior.getThemeColor();
    }

    //获取应用logo
    public static int getAppIconResourceId(){
        return TranslationInterior.getLogoResId();
    }
    //获取埋点接口
    public static TrackerListener getTrackerListener(){
        return TranslationInterior.getTrackerListener();
    }

    //获取点击事件接口
    public static HomeFun getHomeFunListener(){
        if(homeFunListener==null)return new HomeFun() {

            @Override
            public void funType(Context context, FunType funType) {

            }

            @Override
            public boolean isVip() {
                return true;
            }

            @Override
            public void startActivity(Activity context, ActivityOptionsCompat compat, FunType funType) {
                //重启本APP
                Intent iLaunchMyself = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
                iLaunchMyself.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(iLaunchMyself);
            }

            @Override
            public void clickType(Context context, FunType funType) {
                //重启本APP
                Intent iLaunchMyself = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
                iLaunchMyself.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(iLaunchMyself);
            }
        };
        return homeFunListener;
    }

    public static RecordFileCallback getRecordFileCallback() {
        return TranslationInterior.getRecordFileCallback();
    }

    //获取application上下文
    public static Context getTransApplicationContext() {
        return AppContextProvider.getContext();
    }

    public static void setTransApplicationContext(Context context) {
        if (!TranslationEntry.getInstance().isInitialized()){
            AppContextProvider.init(context);
        }
    }

    public static String getAndroidId(){
        return TranslationInterior.getAndroidId();
    }
    public static String getProductInfo(){
        return TranslationInterior.getProductInfo();
    }

    public static String getProductId(){
        return TranslationInterior.getProductId();
    }

    public static String getChannel(){
        return TranslationInterior.getChannel();
    }

    public static String getCredits() {
        return TranslationInterior.getCredits();
    }

    public static int getAppVersion() {
        return TranslationInterior.getAppVersion();
    }

    public static String getAppVersionName() {
        return TranslationInterior.getAppVersionName();
    }

    @Deprecated
    public static boolean isOpenDomainSwitch(){
        return isOpenDomainSwitch;
    }

    public static boolean isDebug(){
        return TranslationInterior.isDebug();
    }


    public static String getAppPackgeName() {
        return AppContextProvider.getContext().getPackageName();
    }

    public static void updateUserInfo(UserInfoBean userInfoBean){
        PreferenceMgr.getInstance().setUserInfo(userInfoBean);
    }

    public static void setSensitiveWords(List<String> words){
        SensitiveWordsCheck.INSTANCE.setSensitiveWords(words);
    }

    @NonNull
    public static List<String> getSensitiveWords() {
        return SensitiveWordsCheck.INSTANCE.getSensitiveWords();
    }

    public static void setIsOpenOfflineTrans(boolean isOpen){
        PreferenceMgr.getInstance().setOpenOfflineTrans(isOpen);
    }

    public static boolean isOpenOfflineTrans(){
        return PreferenceMgr.getInstance().isOpenOfflineTrans();
    }

    //释放阿里语音对象资源
    @Deprecated
    public static void releaseNlsClient() {
    }

    //初始化阿里语音识别，消耗资源，全局建议初始化一次。
    @Deprecated
    public static void resetNlsClient() {
    }

    protected TransInit(Builde builder) {
        TranslationEntry.getInstance().init(
                builder.mContext,
                builder.useTest,
                translationPropertyBuilder.build(),
                themePropertyBuilder.build(),
                callbackPropertyBuilder.build()
        );
    }

    public static Builde Builder(Context context) {
        return new Builde(context);
    }

    public static void initialize() {
        //初始化数据
        initDB();
        //获取tips
        getLanguageTips();
        //主备确定
        testUrl();
    }

    private static void testUrl() {
        ThreadPoolWrapper.getInstance().excuseThread(() -> {
                DomainManager.INSTANCE.setDomainTargets(
                        DomainManager.Domain.app_xunjiepdf_com,
                        DomainManager.Domain.xiaomaai_nnxieli_com,
                        DomainManager.Domain.api_xunjietupian_com);
                DomainManager.INSTANCE.setHttps(true);
                DomainManager.INSTANCE.setProductId(TranslationInterior.getProductId());
                DomainManager.INSTANCE.startDomainTestAsyn(() -> {
                    Pair<String, Boolean> pair = DomainManager.INSTANCE.getDomainUrl(DomainManager.Domain.app_xunjiepdf_com);
                    UrlConstant.BASE_URL_PRODUCTION = pair.first+"/";
                    LogUtil.i("旧翻译接口地址："+UrlConstant.BASE_URL_PRODUCTION);

                    Pair<String, Boolean> pair2 = DomainManager.INSTANCE.getDomainUrl(DomainManager.Domain.xiaomaai_nnxieli_com);
                    UrlConstant.BASE_TRANSLATION_API_URL = pair2.first+"/";
                    LogUtil.i("新翻译接口地址："+UrlConstant.BASE_TRANSLATION_API_URL);

                    Pair<String, Boolean> pair3 = DomainManager.INSTANCE.getDomainUrl(DomainManager.Domain.api_xunjietupian_com);
                    UrlConstant.V4_API_URL_RELEASE = pair3.first+"/";
                    LogUtil.i("V4_API_URL："+UrlConstant.V4_API_URL_RELEASE);
                    LogUtil.d("主备域名初始化完成");
                    startTaskService();
                });
        });

    }

    private static void startTaskService(){
        NetworkTaskService.getInstance().start();
    }

    private static void getLanguageTips() {
        ThreadPoolWrapper.getInstance().excuseThread(() -> {
            InputStream is = null;
            try {
                is = AppContextProvider.getContext().getAssets().open("languages_tips.json");
                String str = IOUtils.toString(is);
                Gson gson = new Gson();
                List<LanguageTips> listLanguageTip = gson.fromJson(str, new TypeToken<List<LanguageTips>>() {
                }.getType());

                languageTipsMap = new HashMap<>();
                for(LanguageTips languageTips:listLanguageTip){
                    languageTipsMap.put(languageTips.getName(), languageTips);
                }
                listLanguageTip.clear();
                LogUtil.d("语言tips初始化完成");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(is);
            }
        });
    }


    private static void initDB() {
        DataBaseMgr.init(AppContextProvider.getContext());
        int daoVersion = PreferenceMgr.getInstance().getDaoVersion();//数据库版本
        int languageVersion = PreferenceMgr.getInstance().getLanguageVersion();//language.json版本
        int version = PreferenceMgr.getInstance().getAppVersion();//应用版本
        List<HuDunLanguage> allLanguages = DataBaseMgr.getInstance().getAllLanguages(true);//获取现有的所有语言
        if (allLanguages.isEmpty()
                || daoVersion != DaoMaster.SCHEMA_VERSION
                || languageVersion != Constant.LANGUAGE_VERSION
                || version != TranslationInterior.getAppVersion()){
            PreferenceMgr.getInstance().saveDaoVersion(DaoMaster.SCHEMA_VERSION);
            PreferenceMgr.getInstance().setLanguageVersion(Constant.LANGUAGE_VERSION);
            PreferenceMgr.getInstance().setAppVersion(TranslationInterior.getAppVersion());
            ThreadPoolWrapper.getInstance().excuseThread(() -> {
                InputStream is = null;
                try {
                    is = AppContextProvider.getContext().getAssets().open("languages.json");
                    String str = IOUtils.toString(is);
                    Gson gson = new Gson();
                    List<HuDunLanguage> list = gson.fromJson(str, new TypeToken<List<HuDunLanguage>>() {
                    }.getType());
                    if(!allLanguages.isEmpty()) {
                        //如果现有的语言不为空，那么就把现有的语言的id赋值给新的语言。否则其他表格的旧数据关联不上
                        for (HuDunLanguage newLanguage : list) {
                            HuDunLanguage oldLanguage = DataBaseMgr.getInstance().getLanguageByTransCode(newLanguage.getTranslateCode());
                            if(oldLanguage != null){
                                newLanguage.setId(oldLanguage.getId());
                            }
                        }
                        LogUtil.d("更新了语言数据库表格");
                    }
                    //过滤一些被禁止使用的语种
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                        list.removeIf(new Predicate<HuDunLanguage>(){

                            @Override
                            public boolean test(HuDunLanguage huDunLanguage) {
                                if(disableLanguages != null){
                                    return disableLanguages.contains(huDunLanguage.getTranslateCode());
                                }else {
                                    return false;
                                }
                            }
                        });
                    }
                    DataBaseMgr.getInstance().deleteAllLanguages();//清空表格
                    DataBaseMgr.getInstance().addLanguages(list);//重新填入

                    HuDunLanguage jan = DataBaseMgr.getInstance().getLanguageByTransCode("ja");
                    HuDunLanguage cn = DataBaseMgr.getInstance().getLanguageByName("zh");
                    HuDunLanguage en = DataBaseMgr.getInstance().getLanguageByName("en");

                    //语言选择弹窗中的常用语言配置（语音翻译）
                    DataBaseMgr.getInstance().addLanguageRecord(jan, true);
                    DataBaseMgr.getInstance().addLanguageRecord(en, true);
                    DataBaseMgr.getInstance().addLanguageRecord(cn, true);

                    //语言选择弹窗中的常用语言配置（文本翻译）
                    DataBaseMgr.getInstance().addLanguageRecord(jan, false);
                    DataBaseMgr.getInstance().addLanguageRecord(en, false);
                    DataBaseMgr.getInstance().addLanguageRecord(cn, false);

                    //数据库初始化完成
                    LogUtil.d("数据库初始化完成");
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    IOUtils.closeQuietly(is);
                }
            });

            //开页默认显示语种
            PreferenceMgr.getInstance().getTranslatePreference().saveTansFromLanguage("英语");
            PreferenceMgr.getInstance().getTranslatePreference().saveTansToLanguage("中文（简体）");
            PreferenceMgr.getInstance().getTranslatePreference().saveFileFromLanguage("英语");
            PreferenceMgr.getInstance().getTranslatePreference().saveFileToLanguage("中文（简体）");
            PreferenceMgr.getInstance().getTranslatePreference().saveVoiceFromLanguage("英语");
            PreferenceMgr.getInstance().getTranslatePreference().saveVoiceToLanguage("中文（简体）");
            LogUtil.d("开页默认显示语种初始化完成");
        }
    }

    @Deprecated
    public static class Builde {

        private final Context mContext;
        private boolean useTest;

        public Builde(Context context) {
            mContext = context;
        }

        public Builde setDisableLanguages(List<String> list){
            disableLanguages.clear();
            disableLanguages.addAll(list);
            return this;
        }

        /**
         * 返回配置信息对象
         */
        public TransInit build() {
            return new TransInit(this);
        }

        /**
         * 设置主体颜色 "#0084ff"
         */
        public Builde setThemeColor(String color) {
            if (!TextUtils.isEmpty(color) && color.trim().matches("^#([a-fA-F\\d]{6}|[a-fA-F\\d]{8})$")) {
                themePropertyBuilder.setThemeColor(Color.parseColor(color));
            }
            return this;
        }

        /**
         * 设置logo
         * @param imageId 例如：R.mipmap.app_icon
         */
        public Builde setAppIconResourceId(int imageId){
            if(imageId!=-1){
                themePropertyBuilder.setLogoResId(imageId);
            }
            return this;
        }

        /**
         * 埋点回调接口
         * @param listener
         * @return
         */
        public Builde setTrackerListener(TrackerListener listener){
            callbackPropertyBuilder.setTrackerListener(listener);
            return this;
        }

        /**
         * 点击时间回调接口
         * @param listener
         * @return
         */
        @Deprecated
        public Builde setHomeFunListener(HomeFun listener){
            homeFunListener = listener;
            return this;
        }

        /**
         * 同声传译回调接口
         * @param listener
         * @return
         */
        public Builde setRecordFileCallback(RecordFileCallback listener){
            callbackPropertyBuilder.setRecordFileCallback(listener);
            return this;
        }
        /**
         * 限制使用回调接口
         * @param listener
         * @return
         */
        public Builde setLimitUseListener(LimitUseListener listener){
            callbackPropertyBuilder.setLimitUseListener(listener);
            return this;
        }

        /**
         * 设备唯一标识
         */
        public Builde setAndroidId(String id){
            translationPropertyBuilder.setAndroidId(id);
            return this;
        }

        /**
         * 是否开启域名交换机开关
         */
        @Deprecated
        public Builde setIsOpenDomainSwitch(boolean isOpen){
            isOpenDomainSwitch = isOpen;
            return this;
        }

        /**
         * 是否开启离线翻译开关
         */
        @Deprecated
        public Builde setIsOpenOfflineTrans(boolean isOpen){
            PreferenceMgr.getInstance().setOpenOfflineTrans(isOpen);
            return this;
        }

        /**
         * 是否开启华为服务开关
         */
        @Deprecated
        public Builde setIsOpenHuaweiService(boolean isOpen){
            isOpenHuaweiService = isOpen;
            return this;
        }

        /**
         * productInfo
         */
        public Builde setProductInfo(String info){
            translationPropertyBuilder.setProductInfo(info);
            return this;
        }

        public Builde setAppVersion(int version){
            translationPropertyBuilder.setAppVersion(version);
            return this;
        }

        public Builde setAppVersionName(String version){
            translationPropertyBuilder.setAppVersionName(version);
            return this;
        }

        public Builde setCredits(String credits){
            translationPropertyBuilder.setProductCredits(credits);
            return this;
        }

        /**
         * productId
         */
        public Builde setProductId(int id) {
            translationPropertyBuilder.setProductId(String.valueOf(id));
            return this;
        }

        /**
         * channel
         */
        public Builde setChannel(String channelName) {
            translationPropertyBuilder.setChannel(channelName);
            return this;
        }

        /**
         * userTest
         */
        public Builde setDebug(boolean isDebug){
            useTest = isDebug;
            return this;
        }

    }
}
